﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using AjaxControlToolkit;

namespace MTRC.ODMS.Web.SOM.Popup {
    public partial class PopupUserQueryStation : BasePage_SOM {

        #region Property
        protected int CriteriaID {
            get {
                if (ViewState["CriteriaID"] != null) {
                    return int.Parse(ViewState["CriteriaID"].ToString());
                }
                else {
                    return 0;
                }
            }
            set {
                ViewState["CriteriaID"] = value;
            }
        }
        #endregion

        #region Function Property
        public string MenuID
        {
            get
            {
                return string.Concat(this.ViewState["_menuID"]);
            }
            set
            {
                this.ViewState["_menuID"] = value;
            }
        }
        public string AllAccessStationID
        {
            get
            {
                return string.Concat(this.ViewState["_allAccessStationID"]);
            }
            set
            {
                this.ViewState["_allAccessStationID"] = value;
            }
        }
        public string OtherAccessStationID
        {
            get
            {
                return string.Concat(this.ViewState["_otherAccessStationID"]);
            }
            set
            {
                this.ViewState["_otherAccessStationID"] = value;
            }
        }
        #endregion

        public static DataTable dt;
        #region  Page Load and UnLoad

        protected override void OnInit(EventArgs e) {
            base.OnInit(e);
            this.ChangeLanguage += new ChangeLanguageEventHandler(ChangeLanguage_Function);
            this.grdSearchResult.RowDeleting += new GridViewDeleteEventHandler(grdSearchResult_RowDeleting);
            this.grdSearchResult.NeedDataBind += new APJ.Web.UI.WebControls.CommonGridView.NeedDataBindHandler(grdSearchResult_NeedDataBind);
        }

        protected void Page_Load(object sender, EventArgs e) {

            if (!IsPostBack) {

                // add by dylan 20151030 for u275.1 
                this.grdSearchResult.PageSize = this.GridViewPageDefaultSize();

                if (Request.QueryString["criteriaID"] != null && Request.QueryString["criteriaID"].ToString() != string.Empty)
                {
                    int critrariaID = 0;
                    int.TryParse(HttpUtility.UrlDecode(Request.QueryString["criteriaID"]), out critrariaID);
                    CriteriaID = critrariaID;
                }

                if (Request.QueryString["MenuID"] != null && Request.QueryString["MenuID"].ToString() != string.Empty)
                {
                    this.MenuID = Request.QueryString["MenuID"];
                }

                if (Request.QueryString["AllAccessStationID"] != null && Request.QueryString["AllAccessStationID"].ToString() != string.Empty)
                {
                    this.AllAccessStationID = Request.QueryString["AllAccessStationID"];
                }

                if (Request.QueryString["OtherAccessStationID"] != null && Request.QueryString["OtherAccessStationID"].ToString() != string.Empty)
                {
                    this.OtherAccessStationID = Request.QueryString["OtherAccessStationID"];
                }

                string stationId = string.Empty;
                if (Request.QueryString["StationId"] != null && Request.QueryString["StationId"].ToString() != string.Empty)
                {
                    stationId = Request.QueryString["StationId"];
                }
                
                //set control text about multi-language of page
                SetLanguage();

                if (Session["station"] != null)
                    dt = Session["station"] as DataTable;
                else
                {
                    dt = DAL.SOM.PassengerFlow.PassengerSelectionCriteria.GetStationData(this.CriteriaID, this.LangCode);
                    if (dt.Rows.Count==0 && stationId.Trim()!="0")
                    {
                        dt = DAL.SOM.PassengerFlow.PassengerSelectionCriteria.GetStationDataByCriteriaIDAndLocationID(this.CriteriaID,Convert.ToInt32(stationId),this.LangCode);
                    }

                }
                
                
                //Custom element initial state of page 
                CustomInitializtion();
            }
            ScriptManager.RegisterStartupScript(Page, typeof(string), "", "InitCombobox();", true);
        }

        #endregion

        #region Event

        public void ChangeLanguage_Function(object sender, EventArgs e) {
            //set control text about multi-language of page

            SetLanguage();
            if (IsPostBack) //added by huangyao 20090120
            {
                CustomInitializtion();
            }
            //bind the seach result
            //BindSearchResult();
        }

        protected void grdSearchResult_RowDataBound(object sender, GridViewRowEventArgs e) {
            if (e.Row.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow) {

            }
        }

        /// <summary>
        /// deal the delete event of gridview
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grdSearchResult_RowCommand(object sender, GridViewCommandEventArgs e) {

            if (e.CommandName.ToUpper() == ("delete").ToUpper()) {
                //DAL.SOM.PassengerFlow.PassengerSelectionCriteria.DelCriteriaStationData(id);
                for (int i = 0; i < dt.Rows.Count; i++) {
                    if ((dt.Rows[i]["UserQueryCriteriaID"].ToString().Trim() + "-" + dt.Rows[i]["LocationID"].ToString().Trim()) == e.CommandArgument.ToString().Trim()) {
                        dt.Rows.RemoveAt(i);
                    }
                }
            }
            grdSearchResult_NeedDataBind();
        }

        protected void grdSearchResult_RowDeleting(object sender, GridViewDeleteEventArgs e) {

        }

        protected void btnSave_Click(object sender, EventArgs e) {

            string PersonHoldStationKye = string.Empty;
            if (dt.Rows.Count > 0) {
                for (int i = 0; i < dt.Rows.Count; i++) {
                    PersonHoldStationKye += dt.Rows[i]["LocationID"] + ",";
                }
                PersonHoldStationKye = PersonHoldStationKye.Remove((PersonHoldStationKye.Length - 1));
                Session["station"] = dt;
            }
            //dt.Rows.Clear();
            if (string.IsNullOrEmpty(PersonHoldStationKye)) {
                this.PAlert(this.GetMessage("SOM_PassengerFlow_AtleastOneStation"));
                return;
            }

            ToolkitScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "", "PersonHoldStation('" + HttpUtility.HtmlDecode(PersonHoldStationKye) + "');", true); 
        }

        protected void btnAddNew_Click(object sender, EventArgs e) {

            if (string.IsNullOrEmpty(this.txtSelectedValue.Text.Trim()))
            {
                this.PAlert(this.GetMessage("SOM_StationCode"));
                return;
            }

            ListItem lstItem;
            string strSelectValue = string.Empty;
            if (this.txtSelectedValue.Text.Trim().ToString().Contains("-"))
            {
                strSelectValue = this.txtSelectedValue.Text.Trim().Split('-')[1];
                lstItem = this.ddlStation.Items.FindByValue(strSelectValue);
            }
            else
            {
                strSelectValue = this.txtSelectedValue.Text.Trim();
                lstItem = this.ddlStation.Items.FindByText(strSelectValue);
            }
            
            if (lstItem == null)
            {
                this.PAlert(this.GetMessage("SOM_LegalStationCheck"));
                return;
            }

            int locationID = Convert.ToInt32(this.ddlStation.SelectedValue);
            int isExists = 0;
            for (int i = 0; i < dt.Rows.Count; i++) {
                if (dt.Rows[i]["LocationID"].ToString() == locationID.ToString() && (Convert.ToString(this.CriteriaID) == dt.Rows[i]["UserQueryCriteriaID"].ToString())) {
                    isExists = 1;
                }
            }

            if (isExists == 0) {
                DataTable dtCriteriaStation = DAL.SOM.PassengerFlow.PassengerSelectionCriteria.GetStationDataByCriteriaIDAndLocationID(this.CriteriaID, locationID, this.LangCode);
                if (dtCriteriaStation.Rows.Count == 1) {
                    DataRow dr = dt.NewRow();
                    dr["UserQueryCriteriaID"] = dtCriteriaStation.Rows[0]["UserQueryCriteriaID"];
                    dr["LocationID"] = dtCriteriaStation.Rows[0]["LocationID"];
                    dr["LocationCode"] = dtCriteriaStation.Rows[0]["LocationCode"];
                    dr["LocationDescription"] = dtCriteriaStation.Rows[0]["LocationDescription"];

                    dt.Rows.Add(dr);
                }
            }
            //DAL.SOM.PassengerFlow.PassengerSelectionCriteria.AddCriteriaSttionData(this.CriteriaID, locationID);
            grdSearchResult_NeedDataBind();

            //Comment by jack 20150906 for U191
            this.txtSelectedValue.Text = "";
            FunctionItemSetting();//bind station
        }

        protected void btnClear_Click(object sender, EventArgs e)
        {
            this.txtSelectedValue.Text = "";
            this.FindByTextAndSelect(ddlStation, "");
            this.ClientScript.RegisterStartupScript(typeof(BasePage), "ClearStation", string.Format("<script language='javascript'>ClearStation()</script>"));
        }

        protected void ddlStation_SelectedIndexChanged(object sender, EventArgs e)
        {
            //this.FindByValueAndSelect(ddlStation,this.txtSelectedValue.Text.Split('-')[1]);
        }

        //protected void SelectValue_OnTextChanged(object sender, EventArgs e)
        //{
        //    ddlStation_SelectedIndexChanged(null, null);
        //    ScriptManager.RegisterStartupScript(Page, typeof(string), "", "InitCombobox();", true);
        //}
        #endregion

        #region Method

        /// <summary>
        /// set page element text multi-language
        /// </summary>
        private void SetLanguage() {
            this.lblStationLable.Text = this.GetLabel("SOM_Station", true);
            this.btnAddNew.Text = this.GetLabel("SOM_PassengerFlow_PopupUserQueStation_Add");
            this.grdSearchResult.Columns[0].HeaderText = GetLabel("SOM_PopupUserQueStation_LocationCode");
            this.grdSearchResult.Columns[1].HeaderText = GetLabel("SOM_PopupUserQueStation_LocationDescription");
            this.grdSearchResult.Columns[2].HeaderText = GetLabel("SOM_PopupUserQueStation_Delete");
            this.btnSave.Text = this.GetLabel("COM_Save");
            this.btnCancel.Text = this.GetLabel("COM_Cancel");
            this.btnClear.Text = this.GetLabel("SOM_Clear");
        }

        /// <summary>
        /// Custom element initial state of page
        /// </summary>
        private void CustomInitializtion() {
            FunctionItemSetting();
            grdSearchResult_NeedDataBind();
        }

        /// <summary>
        /// setting user access by function item.
        /// </summary>
        private void FunctionItemSetting() {

            //Bind Station Stop
            if (DAL.Security.User.CanFunctionItemAccess(this.AllAccessStationID, this.ODMUser.UserProfileID, this.MenuID))//access all station.
            {
                //BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, true, Convert.ToInt16(LangCode), this.ODMUser.StationID), false);
                //update by gordon 20151020 U247
                //BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, true, Convert.ToInt16(LangCode), this.ODMUser.StationID),true,"");
                BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, true, Convert.ToInt16(LangCode), this.ODMUser.LocationID), true, "");
            }
            else if (DAL.Security.User.CanFunctionItemAccess(this.OtherAccessStationID, this.ODMUser.UserProfileID, this.MenuID))//Can Access other stations.
            {
                //BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, false, Convert.ToInt16(LangCode), this.ODMUser.StationID), false);
                //update by gordon 20151020 U247
                //BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, false, Convert.ToInt16(LangCode), this.ODMUser.StationID),true,"");
                BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, false, Convert.ToInt16(LangCode), this.ODMUser.LocationID), true, "");
            }
            else
            {
                //update by gordon 20151020 U247
                //BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, false, Convert.ToInt16(LangCode), this.ODMUser.StationID), false);
                BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, false, Convert.ToInt16(LangCode), this.ODMUser.LocationID), false);
                this.ddlStation.Enabled = false;
                this.btnClear.Enabled = false;
                this.btnAddNew.Enabled = false;
            }

        }

        /// <summary>
        /// sorting ,then afresh databind
        /// </summary>
        private void grdSearchResult_NeedDataBind() {
            BindSearchResult();
        }

        /// <summary>
        /// bind the search result for page
        /// </summary>
        private void BindSearchResult() {

            DataTable dtSearchResult = GetSearchResult();
            this.grdSearchResult.GetLabelFunction = new APJ.Web.UI.WebControls.GetLabel(this.GetLabel);
            grdSearchResult.DataSource = dtSearchResult.DefaultView;
            grdSearchResult.DataBind();
        }

        /// <summary>
        /// search DB get data table Collections
        /// </summary>
        /// <returns>get data table of search result</returns>
        private DataTable GetSearchResult() {

            //DataTable dsEnquiry = DAL.SOM.PassengerFlow.PassengerSelectionCriteria.GetStationData(this.CriteriaID, this.LangCode);

            return dt;
        }
        #endregion

    }
}